import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import commonRoutes from './modules/common'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    ...commonRoutes
  ],
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0, left: 0 }
    }
  }
})

router.beforeEach((to, form, next) => {
  const userStore = useUserStore()
  /** 已登录不拦截，route.meta.noLogin不拦截*/
  if (userStore.token) {
    next()
  } else if (to.matched.some(r => r.meta.noLogin)) {
    next()
  } else {
    next({
      name: 'login'
    })
  }
})

router.afterEach((to, from) => {
  // 页面背景颜色
  if (to.meta.backgroundColor !== from.meta.backgroundColor) {
    if (to.meta.backgroundColor) {
      document.body.style.backgroundColor = to.meta.backgroundColor as string
    } else {
      document.body.style.background = 'none'
    }
  }
})

export default router
